package com.ms.qw.jsf.util;

import com.ms.qw.server.infrastructure.persistence.exception.ApplicationException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: agile02
 * Date: 22/11/2010
 * Time: 06:25:23 PM
 * To change this template use File | Settings | File Templates.
 */
public class FileZip {

    private String zipName;
    private List<File> files;

    public FileZip(String zipName, List<File> files) {
        this.zipName = zipName;
        this.files = files;
    }

    List<String> names= new ArrayList<String>();
    public File zip() {
        File zip = null;
        ZipOutputStream zos = null;
        try {
            zip = File.createTempFile(zipName, ".zip");
            zip.deleteOnExit();
            zos = new ZipOutputStream(new FileOutputStream(zip));
            int i = 0;
            for (File file : files) {
                String nombre=file.getName();
                String formatNombre= nombre.substring(0,nombre.lastIndexOf('_'))+nombre.substring(nombre.indexOf('.'),nombre.length());
                if(names.contains(formatNombre)) {
                    System.out.println("error "+file.getName());
                    continue;
                }
                names.add(formatNombre);
                addFileToZip(zos, file, formatNombre);
                i++;
            }
            zos.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException("Error al generar el Zip");

        }
        return zip;
    }

    private void addFileToZip(ZipOutputStream zos, File f, String fileName) throws IOException {
        byte[] readBuffer = new byte[4096];
        int bytesIn = 0;

        FileInputStream fis = new FileInputStream(f);
        ZipEntry anEntry = new ZipEntry(fileName);
        zos.putNextEntry(anEntry);
        while ((bytesIn = fis.read(readBuffer)) != -1) {
            zos.write(readBuffer, 0, bytesIn);
        }
        fis.close();
    }
}
